import dt from '@dt/dt'
import sys from './sys.js'

let logs = []

function getTime() {
  return new Date().getTime()
}

function send(data, sync = false) {
  if (dt.env.env != 'prod') {
    return false
  }
  var client = new XMLHttpRequest()
  // client.timeout = 1500
  client.open("POST", dt.env.statsUrl + "/analysis-user/appLaunchService/send", !
    sync) // 第三个参数表明是同步的 xhr
  client.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
  let headers = dt.server.auth.header() || {}
  Object.keys(headers).forEach(key => {
    client.setRequestHeader(key, headers[key])
  })
  let ext = {
    ...headers,
    appKey: 'dt',
    eventTimestamp: getTime(),
    browserType: sys.getBrowser().type,
    browserVersion: sys.getBrowser().version,
    sessionId: session.time
  }
  delete ext.authorization
  if (dt.userInfo() && dt.userInfo().role) {
    ext.roleId = dt.userInfo().role.roleId
  }
  if (dt.buildInfo() && dt.buildInfo().housesId) {
    ext.buildingId = dt.buildInfo().housesId
  }
  if (dt.buildInfo() && dt.buildInfo().orgId) {
    ext.companyId = dt.buildInfo().orgId
  }
  let datas = [{
    ...data,
    ...ext
  }]
  client.onload = (res) => {
    try {
      let response = JSON.parse(res.target.response)
      if (response.success) {
        console.log('111')
      }
    } catch (err) {}
  }
  client.send(JSON.stringify({ datas }))
}

let session = {
  time: dt.session.get('stats_session'),
  start: () => {
    session.time = getTime()
    dt.session.set('stats_session', session.time)
    send({ eventType: 1 })
  },
  end: (sync = true) => {
    send({ eventType: 2, launchTimestamp: session.time }, sync)
  }
}

let endReq = false,
  startReq = false

function start() {
  if (!startReq) {
    startReq = true
    endReq = false
    session.start()
  }
}

function end() {
  if (!endReq) {
    endReq = true
    startReq = false
    session.end(false)
  }
}

document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    end()
  } else {
    start()
  }
})

window.addEventListener('focus', start, false)
window.addEventListener('blur', end, false)

window.addEventListener('unload', session.end, false)
session.start()

export default {
  send
}